﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.Drawing;

/// <summary>
/// UserManage 的摘要说明
/// </summary>
namespace LongNet.Util
{
    public class UserManage
    {
        /// <summary>
        /// 验证内部用户登录使用的IKey信息和账户信息是否有效
        /// </summary>
        /// <param name="IKeySN">IKey序列号</param>
        /// <param name="UserAccount">内部用户帐号</param>
        /// <returns></returns>
        public static bool VerifyUserInfoAccout(string IKeySN, string UserAccount)
        {
            try
            {
                if (string.IsNullOrEmpty(IKeySN.Trim()))
                {
                    throw new Exception("请确认是否插入电子加密狗！");
                }
                string EncryIKeySN = CommonClass.Encryption(IKeySN, "MD5");
                EncryIKeySN = CommonClass.Encryption(EncryIKeySN, "MD5");
                Result rs = SqlClass.GetDataSet(" select * from UserInfo where IKeyPwd='" + EncryIKeySN.Replace("'", "''") + "' and UserName='" + UserAccount.Replace("'", "''") + "'");

                return VerifyIKeyByResult(rs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        private static bool VerifyIKeyByResult(Result rs)
        {
            if (rs.DataResult.Tables[0].Rows.Count < 1)
            {
                return false;
                //throw new Exception("你所插入的电子狗无效，请到软件服务商注册电子狗！");
            }
            DataRow dr = rs.DataResult.Tables[0].Rows[0];

            int IsVaild = PublicClass.GetInt32Value(dr["IsVaild"]);
            DateTime ValidDateStart = PublicClass.GetDateTimeValue(dr["ValidDateStart"]);
            DateTime ValidDateEnd = PublicClass.GetDateTimeValue(dr["ValidDateEnd"]);
            if (IsVaild == 2)
            {
                return true;
            }
            else if (IsVaild == 1)
            {
                if (DateTime.Today.CompareTo(ValidDateStart) >= 0 && DateTime.Today.CompareTo(ValidDateEnd) <= 0)
                {
                    return true;
                }
                else
                {
                    return false;
                    //throw new Exception("你的加密狗已经过期，请和软件服务商联系！");
                }
            }
            else
            {
                return false;
                //throw new Exception("你的加密狗已经被禁用，请和软件服务商联系！");
            }
        }

        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static Result UserLogin(string username, string password, int ModuleId)
        {
            Result rs = new Result();
            SqlConnection sqlCon = new SqlConnection(Util.SqlHelper.ConnectionString);
            sqlCon.Open();
            try
            {
                string strSql = "select  top 1 *  from  userinfo where username='" + username.Replace("'", "''").Trim() + "' and pswd='" + password.Replace("'", "''").Trim() + "' and state=1";
                SqlDataReader dr = SqlHelper.ExecuteReader(sqlCon, CommandType.Text, strSql);
                if (dr.Read())
                {
                    string uname = dr["username"].ToString();
                    if (uname == username)
                    {
                        int id = Convert.ToInt32(dr["id"].ToString());
                        rs.IsSuccess = true;
                        //用户cookie

                        //  HttpContext .Current .Request .Cookies 

                        HttpCookie user = new HttpCookie("user");
                        user["UserName"] = dr["username"].ToString();
                        user["FullName"] = HttpContext.Current.Server.UrlEncode(dr["FullName"].ToString());
                        user["uid"] = id.ToString();
                        user.Expires = DateTime.Now.AddDays(6);
                        HttpContext.Current.Response.Cookies.Add(user);

                        //上线后把上面删除

                        HttpContext.Current.Session["UID"] = id;
                        HttpContext.Current.Session["UserName"] = dr["username"].ToString();
                        HttpContext.Current.Session["FullName"] = HttpContext.Current.Server.UrlEncode(dr["FullName"].ToString());
                        HttpContext.Current.Session["CNRoles"] = dr["RoleName"].ToString();
                        UserEntityInfo m_UserEntityInfo = new UserEntityInfo();
                        m_UserEntityInfo.ModuleId = ModuleId;
                        m_UserEntityInfo.UserId = PublicClass.GetInt32Value(id);
                        m_UserEntityInfo.UserName = username;
                        m_UserEntityInfo.FullName = dr["FullName"].ToString();
                        m_UserEntityInfo.EntityTableName = dr["EntityTableName"].ToString();
                        m_UserEntityInfo.EntityTableId = PublicClass.GetInt32Value(dr["EntityTableId"]);
                        
                        strSql = "Select RoleUser.*,Role.RoleName From RoleUser left join Role on RoleUser.RoleId=Role.Id where RoleUser.UserId=" + id;
                        dr.Close();
                        dr = SqlHelper.ExecuteReader(sqlCon, CommandType.Text, strSql);
                        while (dr.Read())
                        {
                            m_UserEntityInfo.RoleId.Add(PublicClass.GetInt32Value(dr["RoleId"]));
                            m_UserEntityInfo.RoleName.Add(dr["RoleName"].ToString());
                        }
                        dr.Close();
                        switch (ModuleId)
                        {
                            case 1:
                                m_UserEntityInfo.IsProvince = true;
                                m_UserEntityInfo.ProvinceId = m_UserEntityInfo.EntityTableId;
                                break;
                            case 2:
                                m_UserEntityInfo.IsCity = true;
                                m_UserEntityInfo.CityIds = m_UserEntityInfo.EntityTableId.ToString();
                                m_UserEntityInfo.CityId = m_UserEntityInfo.EntityTableId;
                                break;
                            case 3:
                                m_UserEntityInfo.IsBankInfo = true;
                                m_UserEntityInfo.BankInfoId = m_UserEntityInfo.EntityTableId;
                                break;
                            case 4:
                                m_UserEntityInfo.IsFinance = true;
                                m_UserEntityInfo.FinanceId = m_UserEntityInfo.EntityTableId;
                                strSql = "Select *  From Finance Where Id=" + m_UserEntityInfo.EntityTableId;
                                dr = SqlHelper.ExecuteReader(sqlCon, CommandType.Text, strSql);
                                if (dr.Read())
                                {
                                    m_UserEntityInfo.CityId = PublicClass.GetInt32Value(dr["CityId"]);
                                }
                               
                                break;
                            case 5:
                                m_UserEntityInfo.IsDevcompany = true;
                                m_UserEntityInfo.DevCompanyId = m_UserEntityInfo.EntityTableId;
                                strSql = "Select * From DevCompany Where id = " + m_UserEntityInfo.EntityTableId.ToString();
                                dr = SqlHelper.ExecuteReader(sqlCon, CommandType.Text, strSql);
                                if (dr.Read())
                                {
                                    m_UserEntityInfo.CityId = PublicClass.GetInt32Value(dr["CityId"]);
                                    m_UserEntityInfo.CityIds = (dr["CityIds"]).ToString();
                                }
                                break;
                            case 6:
                                m_UserEntityInfo.IsPropertyDept = true;
                                m_UserEntityInfo.PropertyDeptId = m_UserEntityInfo.EntityTableId;
                                strSql = "Select * From PropertyDept Where id = " + m_UserEntityInfo.EntityTableId.ToString();
                                dr = SqlHelper.ExecuteReader(sqlCon, CommandType.Text, strSql);
                                if (dr.Read())
                                {
                                    m_UserEntityInfo.CityId = PublicClass.GetInt32Value(dr["CityId"]);
                                    m_UserEntityInfo.CityIds = (dr["CityIds"]).ToString();
                                }
                                break;
                            case 7:
                                m_UserEntityInfo.IsCommunity = true;
                                strSql = "Select VillageId,CityId,Id From dbo.VW_Community Where Id=" + m_UserEntityInfo.EntityTableId;
                                dr = SqlHelper.ExecuteReader(sqlCon, CommandType.Text, strSql);
                                if (dr.Read())
                                {
                                    m_UserEntityInfo.CityId = PublicClass.GetInt32Value(dr["CityId"]);
                                    m_UserEntityInfo.VillageId = PublicClass.GetInt32Value(dr["VillageId"]);
                                    m_UserEntityInfo.CommunityId = PublicClass.GetInt32Value(dr["Id"]);
                                }
                                break;
                            case 8:
                                m_UserEntityInfo.IsOwnersCommittee = true;
                                m_UserEntityInfo.OwnersCommitteeId = m_UserEntityInfo.EntityTableId;
                                strSql = "Select Id,VillageId,CityId,CompanyId,PropertyDeptId From dbo.VW_Community Where id in (select CommunityId From OwnersCommittee where Id=" + m_UserEntityInfo.EntityTableId + ")";
                                dr = SqlHelper.ExecuteReader(sqlCon, CommandType.Text, strSql);
                                if (dr.Read())
                                {
                                    m_UserEntityInfo.CityId = PublicClass.GetInt32Value(dr["CityId"]);
                                    m_UserEntityInfo.VillageId = PublicClass.GetInt32Value(dr["VillageId"]);
                                    m_UserEntityInfo.CommunityId = PublicClass.GetInt32Value(dr["Id"]);
                                    m_UserEntityInfo.DevCompanyId = PublicClass.GetInt32Value(dr["CompanyId"]);
                                    m_UserEntityInfo.PropertyDeptId = PublicClass.GetInt32Value(dr["PropertyDeptId"]);
                                }
                                break;
                            default:
                                break;
                        }

                        HttpContext.Current.Session["UserEntityInfo"] = m_UserEntityInfo;                     
                        dr.Close();
                        string sqlstr = "update UserInfo set IsOnline=1,lastLoginTime=getdate(),lastloginIP='" + HttpContext.Current.Request.UserHostAddress + "' where id=" + id.ToString();

                        int effects = SqlHelper.ExecuteNonQuery(sqlCon, CommandType.Text, sqlstr);
                        if (effects < 1)
                        {
                            rs.Msg = "设置在线状态失败";
                        }
                    }
                    else
                    {
                        dr.Close();
                        rs.IsSuccess = false;
                        rs.Msg = "非法登陆";
                    }
                }
                else
                {
                    dr.Close();
                    rs.IsSuccess = false;
                    rs.Msg = "用户名与密码不匹配，或者帐户已被锁定！";
                }

            }
            catch (Exception ex)
            {
                rs.IsSuccess = false;
                rs.Msg = ex.Message;
                throw ex;
            }
            finally
            {
                if (sqlCon.State == System.Data.ConnectionState.Open)
                {
                    sqlCon.Close();
                }
                sqlCon.Dispose();
            }
            return rs;
        }
        /// <summary>
        /// 用户退出
        /// </summary>
        /// <returns></returns>
        public static Result Logout()
        {
            Result rs = new Result();
            SqlConnection sqlCon = new SqlConnection(Util.SqlHelper.ConnectionString);
            sqlCon.Open();
            try
            {
                if (HttpContext.Current.Session["UID"] != null)
                {
                    rs.IsSuccess = true;
                    int id = Convert.ToInt32(HttpContext.Current.Session["UID"]);
                    int effects = SqlHelper.ExecuteNonQuery(sqlCon, CommandType.Text, "update UserInfo set IsOnline=0 where id=" + id.ToString());
                    if (effects < 1)
                    {
                        rs.IsSuccess = false;
                        rs.Msg = "未知异常";
                    }
                    HttpContext.Current.Session["UID"] = null;
                    HttpContext.Current.Session["UserName"] = null;
                    HttpContext.Current.Session["FullName"] = null;
                    HttpContext.Current.Session["UserEntityInfo"] = null;
                    HttpContext.Current.Session.RemoveAll();
                    HttpContext.Current.Request.Cookies["user"].Expires = DateTime.Now.AddHours(-100);
                }
                else
                {
                    rs.IsSuccess = false;
                    rs.Msg = "退出用户无效";
                }
            }
            catch (Exception ex)
            {
                rs.IsSuccess = false;
                rs.Msg = ex.Message;
                throw ex;
            }
            finally
            {
                if (sqlCon.State == System.Data.ConnectionState.Open)
                {
                    sqlCon.Close();
                }
                sqlCon.Dispose();
            }
            return rs;
        }
        /// <summary>
        /// 返回登陆用户的姓名
        /// </summary>
        /// <returns></returns>
        public static string GetMyFullName()
        {
            try
            {
                object objs = HttpContext.Current.Request.Cookies["user"]["FullName"];
                if (objs != null)
                {
                    return HttpContext.Current.Server.UrlDecode(objs.ToString());
                }
                else
                {
                    object obj = HttpContext.Current.Session["FullName"];
                    if (obj != null)
                    {
                        return HttpContext.Current.Server.UrlDecode(obj.ToString());
                    }
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 通过用户ID获取用户的姓名
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public static string GetFullNameByUserID(int UserID)
        {
            try
            {
                if (UserID == 0)
                {
                    return "";
                }
                string strSql = "Select * From UserInfo Where Id=" + UserID.ToString();

                Util.Result rs = SqlClass.GetDataSet(strSql);

                return rs.DataResult.Tables[0].Rows[0]["FullName"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 返回用户ID
        /// </summary>
        /// <returns></returns>
        public static int GetUID()
        {
            object objs = HttpContext.Current.Request.Cookies["User"];
            if (objs != null)
            {
                return Convert.ToInt32(HttpContext.Current.Request.Cookies["User"]["UID"]);
            }
            else
            {
                object obj = HttpContext.Current.Session["UID"];
                if (obj != null)
                {
                    return Convert.ToInt32(obj);
                }
                return 0;
            }
        }      


    } 
}